package com.longrise.android.byjk.plugins.dealsituation.course.video2.study;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.longrise.common.utils.PrintLog;

/**
 * Created by godliness on 2017/6/15.
 * 仅有该一个维护队列
 * 通过构建新的DefendStudy实现维护过程
 */

public final class DefendHandler {

    private static final String TAG = "DefendHandler";

    private static final int MSG_LOOPER_START = 0;
    /**
     * delay time
     */
    public static final int MSG_LOOPER_DELAY = 30000 << 1;

    private DefendH mHandler;
    private Handler.Callback mCallback;

    private DefendHandler() {
        mHandler = new DefendH();
    }

    public static DefendHandler getInstance() {
        return AssistInstance.mDefendHandler;
    }

    private static class AssistInstance {
        private static final DefendHandler mDefendHandler = new DefendHandler();
    }

    private class DefendH extends Handler {

        public DefendH() {
            super(Looper.getMainLooper());
        }

        @Override
        public void handleMessage(Message msg) {
            if (mCallback != null) {
                mCallback.handleMessage(msg);
            }
            sendEmptyMessageDelayed(MSG_LOOPER_START, MSG_LOOPER_DELAY);
        }
    }

    /**
     * 打印 stop -> start
     */
    public void monitor(Handler.Callback callback) {
        this.mCallback = callback;
        start(0);
    }

    /**
     * 开启维护过程  start()之前,定先stop()
     * 打印 stop --> start
     */
    public boolean start(int delay) {
        stop();
        PrintLog.e(TAG, "start");
        if (mCallback == null || mHandler == null) {
            PrintLog.e(TAG, "start false");
            return false;
        }
        mHandler.sendEmptyMessageDelayed(MSG_LOOPER_START, delay);
        return true;
    }

    /**
     * 停止维护过程
     */
    public void stop() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        PrintLog.e(TAG, "stop");
    }

    public interface OnDefend {

        void onDefend(boolean videopass);

        void onError();
    }
}
